package com.example.java.escape.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author : weicai
 * @date : 14:56 2020/11/28
 *
 * 线程工厂和任务执行体的定义，
 * 通过 newThread 方法快速、统一的创建线程任务，
 * 强调线程一定要有特定意义的名称，方便出错时回溯
 */
public class UserThreadFactory implements ThreadFactory {

    private final String namePrefix;

    private final AtomicInteger nextId = new AtomicInteger(1);

    // 定义线程组名称，在使用jstack来排查问题时，非常有帮助
    UserThreadFactory(String whatFeatureOfGroup) {
        namePrefix = "From UserThreadFactory's " + whatFeatureOfGroup + " -worker-";
    }


    @Override
    public Thread newThread(Runnable task) {
        String name = namePrefix + nextId.getAndIncrement();
        Thread thread = new Thread(null, task, name, 0L);
        System.out.println(thread.getName());
        return thread;
    }

    // 任务执行体
    static class Task implements Runnable {
        private final AtomicLong count = new AtomicLong(0L);
        @Override
        public void run() {
            System.out.println("running_" +count.getAndIncrement());
        }
    }
}
